import React from 'react';
import { connect } from 'dva';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, Radio, Divider, Tooltip, Switch, Select } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DictCode from '../../components/DictCode';
import BatchUpload from '../../components/BatchUpload/Index';
import StepItem from '../../components/BatchUpload/StepItem';
import FileUpload from '../../components/BatchUpload/Upload';
import Finish from '../../components/BatchUpload/Finish';

const RadioGroup = Radio.Group;
const { Option } = Select;
const formItemLayout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
@connect(({ addemp, publicdata, loading }) => ({
  uploading: loading.effects['addemp/uploadFileWithProgress'],
  batchQuery: addemp.batchQuery,
  fileId: publicdata.downloadFile.fileId,
  fileName: publicdata.downloadFile.fileName,
  currentStep: addemp.currentStep,
  progressPercent: addemp.progressPercent,
  resultInfo: addemp.resultInfo,
  showProgress: addemp.showProgress,
  productList: addemp.productList,
}))
@Form.create({
  mapPropsToFields(props) {
    const { batchQuery } = props;
    return {
      sendType: Form.createFormField({ value: batchQuery.sendType }),
      isSerSetFlag: Form.createFormField({ value: batchQuery.isSerSetFlag }),
      tempFlag: Form.createFormField({ value: batchQuery.tempFlag }),
      advancedSetFlag: Form.createFormField({ value: batchQuery.advancedSetFlag }),
      pdIds: Form.createFormField({ value: batchQuery.pdIds }),
      citySplitFlag: Form.createFormField({ value: batchQuery.citySplitFlag }),
      dateSplitFlag: Form.createFormField({ value: batchQuery.dateSplitFlag }),
    };
  },
})
class Batch extends React.PureComponent {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'addemp/updateQuery',
      payload: {
        sendType: '1',
        isSerSetFlag: '2',
        tempFlag: '1',
        advancedSetFlag: '2',
        pdIds: ['PDINF_0000000001', 'PDINF_0000000002'],
        citySplitFlag: '1',
        dateSplitFlag: '2',
        progressPercent: 0,
      },
    });
    // 获取模板适用产品
    dispatch({
      type: 'addemp/getPdInfoList',
      payload: {},
    }).then(res => {
      if (res.success && res.data) {
        dispatch({
          type: 'addemp/updateModelData',
          payload: { productList: res.data },
        });
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
    this.clearModel();
  }

  componentWillUnmount() {
    this.clearModel();
  }

  // 重置model
  clearModel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addemp/updateModelData',
      payload: {
        currentStep: 0,
        progressPercent: 0,
        showProgress: false,
        batchQuery: {
          // 批量上传数据
          sendType: '1', // 服务类型
          isSerSetFlag: '2', // 使用服务配置
          tempFlag: '1', // 五险是否一致
          advancedSetFlag: '2', // 是否高级设置
          pdIds: ['PDINF_0000000001', 'PDINF_0000000002'], // 模板适用产品
          citySplitFlag: '1', // 产品执行地
          dateSplitFlag: '2', // 产品开始日期
        },
      },
    });
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addemp/updateModelData',
      payload: { currentStep },
    });
    if (!currentStep) {
      dispatch({
        type: 'addemp/updateModelData',
        payload: {
          currentStep: 0,
          progressPercent: 0,
          showProgress: false,
        },
      });
    }
  };

  // 下一步
  onNext = () => {
    const {
      dispatch,
      form: { validateFields },
      currentStep,
    } = this.props;
    validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'addemp/updateQuery',
          payload: {
            ...values,
          },
        });
        this.setCurrentstep(currentStep + 1);
      }
    });
  };

  // 上传文件：需要携带参数即传：batchQuery
  uploadFile = formData => {
    console.info('批量增员开始');
    console.time('批量增员时间');
    const { dispatch, batchQuery } = this.props;
    const uploadQuery = {
      sendType: batchQuery.sendType,
      isSerSetFlag: batchQuery.isSerSetFlag,
      tempFlag: batchQuery.tempFlag,
      advancedSetFlag: batchQuery.advancedSetFlag,
      pdIds: batchQuery.pdIds,
      citySplitFlag: batchQuery.citySplitFlag,
      dateSplitFlag: batchQuery.dateSplitFlag,
    };
    // 需要携带参数即传：batchQuery，不需要传参可省略
    Object.entries(uploadQuery).forEach(([key, value]) => {
      formData.append(key, value);
    });
    dispatch({
      type: 'addemp/uploadFileWithProgress',
      payload: formData,
    });
  };

  // 选择高级设置
  changeSwitch = check => {
    const { dispatch, form } = this.props;
    const getFilesValues = form.getFieldsValue();
    const advancedSetFlag = check ? '1' : '2';
    dispatch({
      type: 'addemp/updateQuery',
      payload: {
        ...getFilesValues,
        advancedSetFlag,
      },
    });
  };

  render() {
    const isExactDiv = () => (
      <div>
        <Divider dashed style={{ marginTop: 100 }} />
        <p style={{ margin: '0 auto', width: '90%', fontSize: 14, textAlign: 'left' }}>
          说明
          <br />
          1、日期格式 <span style={{ color: '#f90' }}>年/月/日</span>，例2019/1/1；
          <br />
          2、服务配置编号，在客服管理--&gt;
          <a onClick={() => router.push('/customservicemanage/serverconfig/index')}>服务配置</a>
          功能下创建或查找；
          <br />
          3、使用五险不一致模板时，如果申报工资不填写，代表此险种不做。
        </p>
      </div>
    );
    const {
      form,
      uploading,
      currentStep,
      showProgress,
      progressPercent,
      resultInfo,
      batchQuery,
      productList,
    } = this.props;
    const { getFieldDecorator } = form;

    return (
      <PageHeaderWrapper>
        <BatchUpload currentStep={currentStep}>
          <StepItem title="选择模板类型">
            <Form layout="horizontal" style={{ margin: '40px auto 0', maxWidth: 500 }}>
              <Form.Item {...formItemLayout} label="服务类型">
                {getFieldDecorator('sendType')(
                  <RadioGroup
                    options={[{ value: '1', label: '委托' }, { value: '2', label: '派遣/外包' }]}
                  />
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="使用服务配置">
                {getFieldDecorator('isSerSetFlag')(
                  <DictCode inputType="3" dictType="YES_NO_FLAG" />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label={
                  <span>
                    五险是否一致
                    <Tooltip
                      placement="top"
                      title={
                        <div>
                          <p>社保险种开始日期不同或者只做部分险种时可选择否</p>
                        </div>
                      }
                    >
                      <ExclamationCircleOutlined style={{ margin: '0 5px' }} />
                    </Tooltip>
                  </span>
                }
              >
                {getFieldDecorator('tempFlag')(<DictCode inputType="3" dictType="YES_NO_FLAG" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="高级设置">
                {getFieldDecorator('advancedSetFlag', {
                  initialValue: batchQuery.advancedSetFlag,
                })(
                  <div>
                    <Switch
                      checkedChildren="是"
                      unCheckedChildren="否"
                      defaultChecked={batchQuery.advancedSetFlag === '1'}
                      onChange={check => this.changeSwitch(check)}
                    />
                    {batchQuery.advancedSetFlag !== '1' ? (
                      <p style={{ fontSize: 12, color: '#999', marginTop: 10 }}>
                        产品使用不同执行地或开始日期，请点击我
                      </p>
                    ) : (
                      <p />
                    )}
                  </div>
                )}
              </Form.Item>
              {batchQuery.advancedSetFlag === '1' ? (
                <Form.Item
                  {...formItemLayout}
                  label={
                    <span>
                      模板适用产品
                      <Tooltip
                        placement="top"
                        title={
                          <div>
                            <p>单独设置某个产品的信息可选择相应产品</p>
                          </div>
                        }
                      >
                        <ExclamationCircleOutlined style={{ margin: '0 5px' }} />
                      </Tooltip>
                    </span>
                  }
                >
                  {getFieldDecorator('pdIds', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: batchQuery.pdIds,
                  })(
                    <Select placeholder="请选择" mode="multiple">
                      {productList.map(one => (
                        <Option key={one.pdId} value={one.pdId} datas={one}>
                          {one.pdName}
                        </Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              ) : null}
              {batchQuery.advancedSetFlag === '1' ? (
                <Form.Item
                  {...formItemLayout}
                  label={
                    <span>
                      产品执行地
                      <Tooltip
                        placement="top"
                        title={
                          <div>
                            <p>选择分开设置时，每个产品可分别维护执行地、执行方</p>
                          </div>
                        }
                      >
                        <ExclamationCircleOutlined style={{ margin: '0 5px' }} />
                      </Tooltip>
                    </span>
                  }
                >
                  {getFieldDecorator('citySplitFlag')(
                    <RadioGroup
                      options={[
                        { value: '1', label: '统一设置' },
                        { value: '2', label: '分开设置' },
                      ]}
                    />
                  )}
                </Form.Item>
              ) : null}
              {batchQuery.advancedSetFlag === '1' ? (
                <Form.Item
                  {...formItemLayout}
                  label={
                    <span>
                      产品开始日期
                      <Tooltip
                        placement="top"
                        title={
                          <div>
                            <p>选择分开设置时，每个产品可分别维护开始日期</p>
                          </div>
                        }
                      >
                        <ExclamationCircleOutlined style={{ margin: '0 5px' }} />
                      </Tooltip>
                    </span>
                  }
                >
                  {getFieldDecorator('dateSplitFlag')(
                    <RadioGroup
                      options={[
                        { value: '1', label: '统一设置' },
                        { value: '2', label: '分开设置' },
                      ]}
                    />
                  )}
                </Form.Item>
              ) : null}
            </Form>
            <div style={{ marginTop: 100, textAlign: 'center' }}>
              <Button onClick={() => router.goBack()} style={{ marginRight: 8 }}>
                返回
              </Button>
              <Button type="primary" onClick={this.onNext}>
                下一步
              </Button>
            </div>
            <Divider dashed style={{ marginTop: 100 }} />
            <p style={{ margin: '0 auto', width: '90%', fontSize: 14 }}>
              说明
              <br />
              1、一次批量的人员服务类型需要一致；
              <br />
              2、在遇到以下几种情况时需要在增员时使用服务配置：①一个客户下有多个单立户
              ②社保五险缴费方式不同 ③社保五险缴费账户不同 ④大库不用默认社保组合需要指定；
              <br />
              3、社保五险的申报工资不一致或者五险中部分险种不做时，可选择五险不一致模板；
              <br />
              4、社保五险的业务开始年月不一致时，可选择五险不一致模板，如果各险种的日期不填，默认使用业务开始年月。
            </p>
          </StepItem>
          <FileUpload
            title="上传文件"
            currentStep={currentStep}
            setCurrentstep={this.setCurrentstep}
            downloadTempInfo={{
              // 下载模板信息
              params: {
                sendType: batchQuery.sendType,
                isSerSetFlag: batchQuery.isSerSetFlag,
                tempFlag: batchQuery.tempFlag,
                advancedSetFlag: batchQuery.advancedSetFlag,
                pdIds: batchQuery.pdIds,
                citySplitFlag: batchQuery.citySplitFlag,
                dateSplitFlag: batchQuery.dateSplitFlag,
              },
              url: '/csApi/empSendCreateService/download/template',
              type: 'POST',
            }}
            uploadFile={this.uploadFile}
            uploading={uploading}
            // 展示进度条需要的数据
            progressPercent={progressPercent || 0}
            progressTitle={resultInfo.batchName || '批量增员任务'}
            progressVisible={showProgress}
            isExact={isExactDiv}
            limitSize={1}
          />
          <Finish title="完成" resultInfo={resultInfo} setCurrentstep={this.setCurrentstep} />
        </BatchUpload>
      </PageHeaderWrapper>
    );
  }
}

export default Batch;
